﻿#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QSettings>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Init();
}

MainWindow::~MainWindow()
{

    if(NULL != m_ploadChat)
    {
        m_SetClose();
        if(m_ploadChat->isLoaded())
        {
            m_ploadChat->unload();
            delete m_ploadChat;
        }
    }

    if(NULL != m_printer)
    {
        delete m_printer;
        m_printer = NULL;
        qDebug() << "print exit";
    }
    delete ui;
}

void MainWindow::Init()
{
    m_printer = NULL;
    m_nType=0;
    //打印两行
    m_dlgcard = new dlgcard(this);
    m_dlgcard->hide();
    connect(this, &MainWindow::signalDlgcardShow, m_dlgcard, &dlgcard::slotShow, Qt::DirectConnection);
    //打印四行
    m_dlg = new Dialog;
    m_dlg->hide();
    connect(this, &MainWindow::signalDlgShow,m_dlg,&Dialog::slotshow,Qt::DirectConnection);
    //
    m_udpSocket = new QUdpSocket();
    //端口号固定，主程序向此固定的端口号发送数据1000~65535
    bool bBind = m_udpSocket->bind(QHostAddress::LocalHost,60000, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
    if(bBind)
    {
        connect(m_udpSocket,&QUdpSocket::readyRead,this,&MainWindow::slotUdpRecvData,Qt::QueuedConnection);
        qDebug() <<"print m_udpSocket bind success!";
    }
    else
    {
        qDebug() << "print m_udpSocket bind fail!";
    }

    connect(this, &MainWindow::signalParseJson, this, &MainWindow::slotParseJson, Qt::QueuedConnection);
    connect(this, &MainWindow::signalSearch, this, &MainWindow::slotSearch, Qt::QueuedConnection);
    connect(this, &MainWindow::signalExit, this, &MainWindow::slotExit);
    connect(this,&MainWindow::signalTicketPrint,this,&MainWindow::slotTicketPrint,Qt::QueuedConnection);
    QString szCfg = QString("D:/update/tamirobotactivecfg.ini");
    QSettings CfgSet(szCfg, QSettings::IniFormat);
    CfgSet.setIniCodec("GB18030");
    QString szPrintDesc = "";
    m_nType = CfgSet.value("print/select").toInt();
    if(2 == m_nType)
        szPrintDesc = u8"Deli DL-888D";
    else if(3 == m_nType)
        szPrintDesc = u8"小票打印机";
    else
        szPrintDesc = u8"ZDesigner GT800 (ZPL)";

    qDebug() << u8"print 打印机配置为" << szPrintDesc.toUtf8().data();
    QList<QPrinterInfo> list = QPrinterInfo::availablePrinters();
    for (int i=0; i<list.size(); i++)
    {
        QPrinterInfo eachInfo = list.at(i);
        QString strPrinterName = eachInfo.printerName();
        qDebug() << u8"print 打印机列表:" << i << strPrinterName.toUtf8().data();
        if(strPrinterName.contains(szPrintDesc))
        {
            qDebug() << u8"print 找到打印机驱动1=" << strPrinterName;
            m_printer = new QPrinter(eachInfo/*,QPrinter::HighResolution*/);
            qDebug() << u8"print 找到打印机驱动2=" << strPrinterName;
            m_printer->setPageSizeMM(QSize(65,40));
            m_printer->setFullPage(true);
        }
    }
    //zjz TicketPrinter Init
    if(3 == m_nType)
    {
        initTicketPrinterDll();
        qDebug() << "usb auto=" << m_SetUsbportauto();
        qDebug() << "usb Init=" << m_SetInit();
        QTextCodec*codec=QTextCodec::codecForName("UTF-8");
        QTextCodec::setCodecForLocale(codec);
        qDebug() << QStringLiteral("支持中文") << m_SetReadZKmode(0);   //设置支持中文
        //2018.2.7添加转换图片格式函数，将配置图片变为小票打印机可打印的格式
        convertImageTo24Bmp();
    }
    //
    m_szCfgFileName = u8"print_config.txt";
    if(!QFile::exists(m_szCfgFileName))
    {
        QSettings CfgSet(m_szCfgFileName, QSettings::IniFormat);
        CfgSet.setIniCodec("UTF-8");
        CfgSet.beginGroup("print_direction");
        CfgSet.setValue("direction",QString(u8"清空此文件中所有内容，并将Excel编译好的复制到此文件中").toUtf8().data());
        CfgSet.endGroup();
        CfgSet.sync();
    }
}

void MainWindow::slotUdpRecvData()
{
    QByteArray bArry, bOnce;
    int nNeeds= m_udpSocket->pendingDatagramSize();
    while (0 < nNeeds)
    {
        bOnce.resize(nNeeds);
        QHostAddress sender;
        quint16 senderPort;
        m_udpSocket->readDatagram(bOnce.data(),bOnce.size(), &sender, &senderPort);
        bArry += bOnce;
        bOnce.clear();
        nNeeds = m_udpSocket->pendingDatagramSize();
    }
    int nSize = bArry.size();
    QTextCodec *codec = QTextCodec::codecForName("GB2312");
    QString szLine = codec->toUnicode(bArry);
    qDebug() << "print data meaaage=" << szLine.toUtf8().data();

    if(nSize < 10)
        return;
    //recv TmPrinter_Exit
    //TmPrinter_Print:title1,title2,name,company,job,1/2/3,telephone
    //标题第一行，标题第二行，姓名，公司，职位，来宾类型，手机号
    QString dataHead = szLine.left(10);
    if(0 == dataHead.compare("TmPrinter_"))
    {
        QString cmd = szLine.right(szLine.length() - szLine.lastIndexOf('_') - 1);
        //cmd = Exit/Print:title1,title2,name,company,job,1/2/3,telephone
        if(0 == cmd.compare("Exit"))
        {
            emit signalExit();
        }
        else
        {
            //解析收到的json串
            cmd = szLine.right(szLine.length() - szLine.lastIndexOf(':') - 1);
            qDebug() << "print cmd = " << cmd;
            emit signalParseJson(cmd);
        }
    }
}

void MainWindow::slotParseJson(QString szJson)
{
    //szJson = title1,title2,name,company,job,1/2/3,telephone
    QString szTitle1 = szJson.left(szJson.indexOf(',')).simplified();
    szJson = szJson.right(szJson.length() - szJson.indexOf(',') - 1);
    QString szTitle2 = szJson.left(szJson.indexOf(',')).simplified();
    szJson = szJson.right(szJson.length() - szJson.indexOf(',') - 1);
    QString szName = szJson.left(szJson.indexOf(',')).simplified();
    szJson = szJson.right(szJson.length() - szJson.indexOf(',') - 1);
    QString szCompany = szJson.left(szJson.indexOf(',')).simplified();
    szJson = szJson.right(szJson.length() - szJson.indexOf(',') - 1);
    QString szJob = szJson.left(szJson.indexOf(',')).simplified();
    szJson = szJson.right(szJson.length() - szJson.indexOf(',') - 1);
    int uGstType = szJson.left(szJson.indexOf(',')).toInt();
    QString szTel = szJson.right(szJson.length() - szJson.indexOf(',') - 1).simplified();
    qDebug() << "print szTitle1 = " << szTitle1.toUtf8().data() << "szTitle2 = " << szTitle2.toUtf8().data()
             << "szName = "<< szName.toUtf8().data() << "szCompany = "<< szCompany.toUtf8().data()
             << "szJob = " << szJob.toUtf8().data() << "uGstType = " << uGstType
             << "szTel = " << szTel.toUtf8().data();
    if(3 == m_nType)
        emit signalTicketPrint(szTitle1,szTitle2,szName,szCompany,szJob,uGstType,szTel);
    else
        emit signalSearch(szName,szTel);
}

void MainWindow::slotExit()
{
    m_udpSocket->close();
    this->close();
}

void MainWindow::slotSearch(QString name, QString tel)
{
    //判断是否有手机号传过来
    if(tel.length() < 1)
        return;
    //有手机号，先和printed.ini中手机号对比，有，直接return，无，手机号+姓名添加进printed.ini
    QFile filePrinted("printed.ini");
    if(filePrinted.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        int n=0;
        while (!filePrinted.atEnd()) {
            n++;
            QByteArray line = filePrinted.readLine();
            QString strLine(line);
            QString strName,  strTel;
            strName = strLine.left(strLine.indexOf("\t"));
            strLine = strLine.right(strLine.length() - strLine.indexOf("\t") - 1);
            strTel = strLine.left(strLine.indexOf("\n"));
            qDebug() << "print strName=" << strName.toUtf8().data() << "strTel=" << strTel;
            //查找到手机号，直接return
            if(0 == strTel.compare(tel))
                return;
        }
        //未查找到手机号，手机号+name 添加进printed.ini
        QString strAppend = name + "\t" + tel + "\n";
        qDebug() << "print strAppend=" << strAppend;
        filePrinted.write(strAppend.toUtf8().data());
    }

    //和print_config.txt进行对比，有则打印dialog，无则打印dlgcard
    QFile fileCfg(m_szCfgFileName);
    if(fileCfg.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << u8"print open print_config.txt";
        int n=0;
        QString strTitle1,strTitle2,strTitle3,strTitle4;
        while (!fileCfg.atEnd()) {
            n++;
            QByteArray line = fileCfg.readLine();
            QString strLine(line);
            QString str1, str2, str3, str4, strTel;
            str1 = strLine.left(strLine.indexOf("\t"));
            strLine = strLine.right(strLine.length() - strLine.indexOf("\t") - 1);
            str2 = strLine.left(strLine.indexOf("\t"));
            strLine = strLine.right(strLine.length() - strLine.indexOf("\t") - 1);
            str3 = strLine.left(strLine.indexOf("\t"));
            strLine = strLine.right(strLine.length() - strLine.indexOf("\t") - 1);
            str4 = strLine.left(strLine.indexOf("\t"));
            strLine = strLine.right(strLine.length() - strLine.indexOf("\t") - 1);
            strTel = strLine.simplified();
            if(1 == n)
            {
                strTitle1 = str1;
                strTitle2 = str2;
                strTitle3 = str3;
                strTitle4 = str4;
            }
            //查找到手机号，打印dialog
            if(0 == strTel.compare(tel))
            {
                qDebug() << u8"print 匹配定制配置文件str1=" << str1 << "str2=" << str2 << "str3=" << str3 << "str4=" << str4 << "strTel=" << strTel;
                emit signalDlgShow(strTitle1 + str1, strTitle2 + str2, strTitle3 + str3, strTitle4 + str4);
                m_pixmap = new QPixmap(m_dlg->size());
                m_dlg->render(m_pixmap);
                m_pixmap->save("TmPrinter.jpg");
                printInfo();
                return;
            }
        }
        //未查找到手机号，打印dlgcard
        qDebug() << u8"print 匹配定制配置文件失败，常规打印name=" << name.toUtf8().data();
        emit signalDlgcardShow(name);
        m_pixmap = new QPixmap(m_dlgcard->size());
        m_dlgcard->render(m_pixmap);
        m_pixmap->save("TmPrinter.jpg");
        printInfo();
    }
}

void MainWindow::slotTicketPrint(QString title1, QString title2, \
                                 QString name, QString company,  \
                                 QString job, int ntype, QString tel)
{
    //判断是否有手机号传过来
    if(tel.length() < 1)
        return;
    //有手机号，先和printed.ini中手机号对比，有，直接return，无，手机号+姓名添加进printed.ini
    QFile filePrinted("printed.ini");
    if(filePrinted.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        while (!filePrinted.atEnd()) {
            QByteArray line = filePrinted.readLine();
            QString strLine(line);
            QString strName,  strTel;
            strName = strLine.left(strLine.indexOf("\t"));
            strLine = strLine.right(strLine.length() - strLine.indexOf("\t") - 1);
            strTel = strLine.left(strLine.indexOf("\n"));
            qDebug() << "print strName=" << strName.toUtf8().data() << "strTel=" << strTel;
            //查找到手机号，直接return
            if(0 == strTel.compare(tel))
                return;
        }
        //未查找到手机号，手机号+name 添加进printed.ini
        QString strAppend = name + "\t" + tel + "\n";
        qDebug() << "print strAppend=" << strAppend;
        filePrinted.write(strAppend.toUtf8().data());
    }
    printTicketInfo(title1,title2,name,company,job,ntype,tel);
}

void MainWindow::printInfo()
{
    if(NULL == m_printer)
    {
        qDebug() << u8"print 未找到打印机驱动";
        return;
    }
    if(m_painter.begin(m_printer))
    {
        qDebug() << "print begin, printerName=" << m_printer->printerName().toUtf8().data();
        QRect rect = m_painter.viewport();
        QSize size = m_pixmap->size();
        size.scale(rect.size(), Qt::KeepAspectRatio);
        m_painter.setViewport(0, 5, size.width(), size.height());
        m_painter.setWindow(m_pixmap->rect());
        m_painter.drawPixmap(0,0,*m_pixmap);
        m_painter.end();
    }
    else
        qDebug() << "print begin failed!" << m_printer->printerName().toUtf8().data();
}

void MainWindow::initTicketPrinterDll()
{
    QString szLoadDll= QString("MsprintsdkRM.dll");
    m_ploadChat = new QLibrary(szLoadDll);
    if(m_ploadChat->load())
    {
        m_SetPrintport =(SetPrintport)m_ploadChat->resolve("SetPrintport");
        m_SetUsbportauto = (SetUsbportauto)m_ploadChat->resolve("SetUsbportauto");
        m_SetInit = (SetInit)m_ploadChat->resolve("SetInit");
        m_SetClose = (SetClose)m_ploadChat->resolve("SetClose");
        m_SetClean = (SetClean)m_ploadChat->resolve("SetClean");
        m_SetAlignment = (SetAlignment)m_ploadChat->resolve("SetAlignment");
        m_SetSizetext = (SetSizetext)m_ploadChat->resolve("SetSizetext");
        m_SetSizechar = (SetSizechar)m_ploadChat->resolve("SetSizechar");
        m_SetSizechinese = (SetSizechinese)m_ploadChat->resolve("SetSizechinese");
        m_SetLinespace = (SetLinespace)m_ploadChat->resolve("SetLinespace");
        m_SetLeftmargin = (SetLeftmargin)m_ploadChat->resolve("SetLeftmargin");
        m_SetBold = (SetBold)m_ploadChat->resolve("SetBold");
        m_SetSpacechar = (SetSpacechar)m_ploadChat->resolve("SetSpacechar");
        m_SetSpacechinese = (SetSpacechinese)m_ploadChat->resolve("SetSpacechinese");
        m_SetNvbmp = (SetNvbmp)m_ploadChat->resolve("SetNvbmp");
        m_PrintNvmbp = (PrintNvmbp)m_ploadChat->resolve("PrintNvmbp");
        m_PrintSelfcheck = (PrintSelfcheck)m_ploadChat->resolve("PrintSelfcheck");
        m_PrintString = (PrintString)m_ploadChat->resolve("PrintString");
        m_PrintFeedline = (PrintFeedline)m_ploadChat->resolve("PrintFeedline");
        m_PrintQrcode = (PrintQrcode)m_ploadChat->resolve("PrintQrcode");
        m_PrintRemainQR = (PrintRemainQR)m_ploadChat->resolve("PrintRemainQR");
        m_Print1Dbar = (Print1Dbar)m_ploadChat->resolve("Print1Dbar");
        m_PrintQRcode500II = (PrintQRcode500II)m_ploadChat->resolve("PrintQRcode500II");
        m_PrintCutpaper = (PrintCutpaper)m_ploadChat->resolve("PrintCutpaper");
        m_PrintMarkposition = (PrintMarkposition)m_ploadChat->resolve("PrintMarkposition");
        m_PrintMarkcutpaper = (PrintMarkcutpaper)m_ploadChat->resolve("PrintMarkcutpaper");
        m_SetPagemode = (SetPagemode)m_ploadChat->resolve("SetPagemode");
        m_SetPagestartposition = (SetPagestartposition)m_ploadChat->resolve("SetPagestartposition");
        m_PrintPagedata = (PrintPagedata)m_ploadChat->resolve("PrintPagedata");
        m_PrintDiskbmpfile = (PrintDiskbmpfile)m_ploadChat->resolve("PrintDiskbmpfile");
        m_PrintTransmit = (PrintTransmit)m_ploadChat->resolve("PrintTransmit");
        m_GetTransmit = (GetTransmit)m_ploadChat->resolve("GetTransmit");
        m_GetStatus = (GetStatus)m_ploadChat->resolve("GetStatus");
        m_SetReadZKmode = (SetReadZKmode)m_ploadChat->resolve("SetReadZKmode");
        m_GetProductinformation=(GetProductinformation)m_ploadChat->resolve("GetProductinformation");
        m_PrintDiskimgfile=(PrintDiskimgfile)m_ploadChat->resolve("PrintDiskimgfile");
        m_PrintChangeRow=(PrintChangeRow)m_ploadChat->resolve("PrintChangeRow");
    }
    else
    {
        qDebug() << "load fail!";
    }
}

void MainWindow::printTicketInfo(QString title1, QString title2, QString name, QString company, QString job, int type, QString tel)
{
    m_SetClean();
    QTextCodec *gbk = QTextCodec::codecForName("gb18030");
    QSettings set("./ticketConfig.ini",QSettings::IniFormat);
    //参数获取打印信息
    QString logoPath="./print_logo.bmp";//准备好的大小260*120,格式24位位图(bmp)//改进---qt画图
    QString themeStr=title1;
    QString nameStr=name;
    QString typeStr="";//ntype
    QString positionStr=job;
    QString companyStr=company;
    bool haveRemarks=true;         //是否打备注信息
    //从配置文件获取打印信息(会议名称/公司名称/备注信息)(优先选择配置文字打印)
    QString iniThemeStr=gbk->toUnicode(set.value("theme/title").toString().toLatin1());
    if(iniThemeStr!="")
        themeStr=iniThemeStr;
    QString iniCompanyStr=gbk->toUnicode(set.value("theme/company").toString().toLatin1());
    if(iniCompanyStr!="")
        companyStr=iniCompanyStr;
    QString tipsStr=gbk->toUnicode(set.value("theme/tips").toString().toLatin1());
    if(tipsStr=="")
        haveRemarks=false;
    qDebug()<<themeStr<<name<<companyStr<<job<<type<<tel<<tipsStr;
    //操作打印机
    qDebug()<<QStringLiteral("设置支持中文")<<m_SetReadZKmode(0);   //设置支持中文
    m_SetClean();
    //logo图
    m_SetLeftmargin(60);
    m_PrintDiskimgfile(gbk->fromUnicode(logoPath).data());
    m_PrintFeedline(5);
    //会议名称
    m_SetBold(1);
    m_SetLeftmargin(0);
    m_SetAlignment(1);//居中
    //m_SetSizechinese(1,1,0,1);
    m_SetSizetext(2,2);
    m_PrintString(gbk->fromUnicode(themeStr).data(),1);
    m_PrintChangeRow();
    //名字和具体职务
    m_SetBold(0);
    m_PrintFeedline(5);
    m_SetLinespace(10);
    m_PrintString(gbk->fromUnicode(nameStr).data(),0);
    m_PrintFeedline(5);
    m_PrintString(gbk->fromUnicode(typeStr).data(),0);
    m_PrintFeedline(0);
    m_PrintString(gbk->fromUnicode(positionStr).data(),0);
    m_PrintFeedline(0);
    m_PrintString(gbk->fromUnicode(companyStr).data(),0);
    //备注信息
    if(haveRemarks){
        m_PrintFeedline(1);
        m_PrintString(gbk->fromUnicode("----------------").data(),0);//"_______________"
        m_PrintFeedline(2);
        m_SetSizetext(1,1);
        m_PrintString(gbk->fromUnicode(tipsStr),1);
        m_PrintChangeRow();
        m_PrintFeedline(2);
//        m_PrintString(gbk->fromUnicode("----------------").data(),0);//"_______________"
        m_PrintFeedline(5);
    }else
        m_PrintFeedline(10);
    m_PrintCutpaper(0);
}

void MainWindow::convertImageTo24Bmp()
{
    QSettings set("./ticketConfig.ini",QSettings::IniFormat);
    QString photoPath=QTextCodec::codecForName("gb18030")->toUnicode(set.value("theme/photo").toString().toLatin1());
    if(photoPath==""||(!QFileInfo::exists(photoPath))){
        qDebug() << u8"Tami_printer:ticket配置的图片不存在";
//        QFile::remove("./print_logo.bmp");
        return;
    }
    QImage img(photoPath);
    qDebug()<<"TmPrinter_imgFormat:"<<img.format();
    union myrgb
    {
        uint rgba;
        uchar rgba_bits[4];
    };
    myrgb* mybits =(myrgb*) img.bits();
    int len = img.width()*img.height();
    //透明色转白色，否则格式转换中透明的黑变纯黑，导致小票打印机打印图整个变黑
    while(len-->0)
    {
        mybits->rgba =(mybits->rgba_bits[3]==0/*透明*/)?0xffffffff/*白色*/:mybits->rgba;
        mybits++;
    }
    img.convertToFormat(QImage::Format_RGB888);
    img=img.scaled(260,260*img.height()/img.width());
    img.save("./print_logo.bmp","bmp");
}

void MainWindow::on_pushButton_clicked()
{
    //title1,title2,name,company,job,1/2/3,telephone
    QByteArray data = "TmPrinter_Print:第一级标题,第二级标题,姓名,塔米智能,程序员,1,18910098748";
    udptest.writeDatagram(data, QHostAddress::LocalHost, 60000);
}
